package org.developer.client.rpc;

import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;


public class HttpUtil {

    public static synchronized Result callRemoteService(String identifier,String methodName,String argTypes,String argValues) throws Exception {

        try {
            List<NameValuePair> paramList = new ArrayList<>();
            paramList.add(new BasicNameValuePair("identifier",identifier));
            paramList.add(new BasicNameValuePair("methodName",methodName));
            paramList.add(new BasicNameValuePair("argTypes",argTypes));
            paramList.add(new BasicNameValuePair("argValues",argValues));
            //远程调用前的准备，sendPost
            String result = sendPost("http://127.0.0.1:12311/", paramList);
            return JSON.parseObject(result,Result.class);
        }catch (Exception e){
            return Result.getFailResult("触发远程调用失败");
        }

    }

    private static synchronized String sendPost(String url,List<NameValuePair> nameValuePairList) throws Exception {
        // TODO: 2020/3/2 分析 CloseableHttpResponse HttpClientBuilder
        CloseableHttpResponse response = null;
        try {
            //创建 CloseableHttpClient对象
            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            //最终会到达URLEncodedUtils.format这个方法，里面有一个 Stringbuilder，通过构造的方法，构造出 "name = value" 的格式
            StringEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
            post.setEntity(entity);
            //执行远程调用
            response = client.execute(post);
            //获取调用的状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if(200 == statusCode){
                return EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }catch (Exception e){

        }finally {
            if(response != null){
                response.close();
            }
        }

        return null;
    }
}
